<!-- src/view/rawMaterial.vue -->
<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import rawMaterialApi from '../api/rawMaterialApi.js';
import { ElMessage, ElMessageBox } from 'element-plus';

// 完整原材料数据
const tableData = ref([]);

// 分页参数
const page = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value);
});

// 分页显示数据
const pagedData = computed(() => {
  const start = (page.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 查询条件
const query = reactive({
  name: ''
});

// 新增表单
const newRawMaterial = reactive({
  name: '',
  supplierId: null,
  unit: '',
  price: null,
  stockQuantity: null
});

// 编辑对话框控制
const dialogVisible = ref(false);
const editForm = reactive({
  id: null,
  name: '',
  supplierId: null,
  unit: '',
  price: null,
  stockQuantity: null
});

// 加载原材料列表
const loadRawMaterials = async () => {
  try {
    console.log('开始加载原材料列表');
    const res = await rawMaterialApi.list();
    console.log('原材料列表数据:', res);
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      total.value = tableData.value.length;
      console.log('加载的原材料数据:', tableData.value);
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error(res.msg || '加载数据失败');
    }
    page.value = 1; // 重置到第一页
  } catch (err) {
    console.error('加载原材料列表失败:', err);
    tableData.value = [];
    total.value = 0;
    ElMessage.error('加载原材料列表失败: ' + (err.message || '未知错误'));
  }
};

// 查询原材料
const searchRawMaterials = async () => {
  try {
    const res = await rawMaterialApi.list(query);
    if (res && res.code === 200) {
      tableData.value = Array.isArray(res.data) ? res.data : [];
      total.value = tableData.value.length;
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.error(res.msg || '查询失败');
    }
    page.value = 1; // 查询后重置分页
  } catch (err) {
    console.error('查询原材料失败:', err);
    tableData.value = [];
    total.value = 0;
    ElMessage.error('查询原材料失败: ' + (err.message || '未知错误'));
  }
};

// 重置查询
const resetSearch = () => {
  query.name = '';
  loadRawMaterials();
};

// 分页控制
const handlePageChange = (newPage) => {
  page.value = newPage;
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  page.value = 1;
};

const prevPage = () => {
  if (page.value > 1) {
    page.value--;
  }
};

const nextPage = () => {
  if (page.value < totalPages.value) {
    page.value++;
  }
};

// 监听pageSize变化
watch(pageSize, () => {
  page.value = 1; // pageSize变化时回到第一页
});

// 初始化加载数据
onMounted(() => {
  console.log('组件挂载，开始加载原材料数据');
  loadRawMaterials();
});

// 新增原材料
const addRawMaterial = async () => {
  if (!newRawMaterial.name) {
    ElMessage.warning('原材料名称不能为空');
    return;
  }
  try {
    await rawMaterialApi.add(newRawMaterial);
    ElMessage.success('新增原材料成功');
    resetNewRawMaterial();
    loadRawMaterials();
  } catch (err) {
    console.error('新增原材料失败:', err);
    ElMessage.error('新增原材料失败: ' + (err.message || '未知错误'));
  }
};

// 打开编辑对话框
const openEditDialog = (rawMaterial) => {
  Object.assign(editForm, rawMaterial);
  dialogVisible.value = true;
};

// 提交编辑
const submitEdit = async () => {
  if (!editForm.id) {
    ElMessage.warning('原材料ID不存在');
    return;
  }
  try {
    const { id, ...updateData } = editForm;
    await rawMaterialApi.edit(id, updateData);
    dialogVisible.value = false;
    ElMessage.success('更新原材料成功');
    loadRawMaterials();
  } catch (err) {
    console.error('更新原材料失败:', err);
    ElMessage.error('更新原材料失败: ' + (err.message || '未知错误'));
  }
};

// 删除原材料
const confirmDelete = async (id) => {
  ElMessageBox.confirm('确定要删除该原材料吗？此操作不可恢复。', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await rawMaterialApi.del(id);
      ElMessage.success('删除成功');
      loadRawMaterials();
    } catch (err) {
      console.error('删除失败:', err);
      ElMessage.error('删除失败: ' + (err.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 重置新增表单
const resetNewRawMaterial = () => {
  newRawMaterial.name = '';
  newRawMaterial.supplierId = null;
  newRawMaterial.unit = '';
  newRawMaterial.price = null;
  newRawMaterial.stockQuantity = null;
};
</script>

<template>
  <div>
    <h1>原材料管理</h1>

    <!-- 查询原材料 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>查询原材料</span>
        </div>
      </template>
      <el-form :inline="true" :model="query">
        <el-form-item label="原材料名称">
          <el-input v-model="query.name" placeholder="原材料名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchRawMaterials">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增原材料 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>新增原材料</span>
        </div>
      </template>
      <el-form :inline="true" :model="newRawMaterial" label-width="120px">
        <el-form-item label="原材料名称">
          <el-input v-model="newRawMaterial.name" placeholder="原材料名称" />
        </el-form-item>
        <el-form-item label="供应商ID">
          <el-input v-model.number="newRawMaterial.supplierId" placeholder="供应商ID" type="number" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="newRawMaterial.unit" placeholder="单位" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="newRawMaterial.price" placeholder="价格" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model.number="newRawMaterial.stockQuantity" placeholder="库存数量" type="number" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addRawMaterial">添加</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 原材料表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>原材料列表</span>
        </div>
      </template>
      <el-table :data="pagedData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="原材料名称" />
        <el-table-column prop="supplierId" label="供应商ID" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="stockQuantity" label="库存数量" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 当没有数据时显示提示 -->
      <div v-if="tableData.length === 0" style="text-align: center; margin-top: 20px;">
        <p>暂无数据</p>
      </div>

      <!-- 分页 -->
      <div v-if="tableData.length > 0" style="margin-top: 20px; text-align: right;">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 编辑原材料对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑原材料" width="500px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="原材料名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="供应商ID">
          <el-input v-model.number="editForm.supplierId" type="number" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="editForm.unit" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="editForm.price" type="number" step="0.01" />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input v-model.number="editForm.stockQuantity" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>